//
//  KFDRegisterViewController.m
//  
//
//  Created by JIRENTIANXIANG on 6/15/15.
//
//

#import "KFDRegisterViewController.h"
#import "KFDUIConfigurator.h"
#import "ui_config.h"
#import "UIButton+KFD.h"
#import "KFDAccountManager.h"
#import "JTToast.h"
#import "KFDSetNicknamePasswordViewController.h"

typedef NS_ENUM(unsigned int, TextFieldTag){
    REAL_NAME_TEXT_FIELD,
    PHONE_NUMBER_TEXT_FIELD,
    CHECKCODE_TEXT_FIELD
};

@interface KFDRegisterViewController ()<UITextFieldDelegate>

@property (strong,nonatomic) KFDUIConfigurator* uiConfigurator;

@property (weak, nonatomic) IBOutlet UIButton *checkcodeButton;

@property (weak, nonatomic) IBOutlet UITextField *realNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *checkcodeTextField;

@property (strong,nonatomic) NSTimer* timer;

@end

@implementation KFDRegisterViewController
{
    int _countdown;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.uiConfigurator=[KFDUIConfigurator configuratorForViewController:self];
    [self.uiConfigurator configureNavigationBarWithBackAction:@selector(goBack)];
    self.title=@"注册";
    self.view.backgroundColor=KFD_BG_COLOR;
    [self configureTextFields];
    [self configureFooterView];
    _countdown=60;
}

-(void)configureTextFields
{
    self.realNameTextField.tag=REAL_NAME_TEXT_FIELD;
    self.phoneNumberTextField.tag=PHONE_NUMBER_TEXT_FIELD;
    self.checkcodeTextField.tag=CHECKCODE_TEXT_FIELD;
    
    self.realNameTextField.delegate=self;
    self.phoneNumberTextField.delegate=self;
    self.checkcodeTextField.delegate=self;
}

-(void)configureFooterView
{
    UIView* footerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.uiConfigurator.WIDTH, 100)];
    UIButton* nextButton=[UIButton redButtonWithtitle:@"设置昵称和密码"];
    nextButton.center=CGPointMake(self.uiConfigurator.WIDTH*0.5, 40);
    [nextButton addTarget:self action:@selector(nextButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:nextButton];
    self.tableView.tableFooterView=footerView;
}

- (IBAction)checkcodeButtonPressed:(id)sender {
    [self.phoneNumberTextField resignFirstResponder];
    [self.checkcodeTextField resignFirstResponder];
    NSString* phoneNumber=self.phoneNumberTextField.text;
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    if ([accountManager checkPhoneNumber:phoneNumber illegalInputHandler:^(NSString *message) {
        [[JTToast makeText:message] showInView:self.view size:CGSizeMake(message.length*20, 40)];
    }]) {
        [accountManager getCheckcodeForRegistrationWithPhoneNumber:phoneNumber successHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                self.checkcodeButton.userInteractionEnabled=false;
                [self.checkcodeButton setTitle:@"60秒" forState:UIControlStateNormal];
                self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countdown) userInfo:nil repeats:YES];
            });
        } failureHandler:^(KFDResponseBody *response) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[JTToast makeText:response.message] showInView:self.view size:CGSizeMake(response.message.length*20, 40)];
            });
        }];
    }
}

-(void)countdown
{
    _countdown-=1;
    [self.checkcodeButton setTitle:[NSString stringWithFormat:@"%d秒",_countdown] forState:UIControlStateNormal];
    if (_countdown==0) {
        _countdown=60;
        [self.timer invalidate];
        self.checkcodeButton.userInteractionEnabled=YES;
        [self.checkcodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
}

-(void)nextButtonPressed
{
//#define SKIP_REGISTRATION
#ifdef SKIP_REGISTRATION
    KFDSetNicknamePasswordViewController* setNicknamePasswordVC=[[UIStoryboard storyboardWithName:@"SetNicknamePassword" bundle:nil] instantiateViewControllerWithIdentifier:@"KFDSetNicknamePasswordViewController"];
    setNicknamePasswordVC.sourceViewController=self.sourceViewController;
    [self.navigationController pushViewController:setNicknamePasswordVC animated:YES];
#else
    NSString* realName=self.realNameTextField.text;
    NSString* phoneNumber=self.phoneNumberTextField.text;
    NSString* checkcode=self.checkcodeTextField.text;
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    if ([accountManager checkRealName:realName illegalInputHandler:^(NSString *message) {
        [[JTToast makeText:message] showInView:self.view size:CGSizeMake(message.length*20, 40)];
    }]) {
        if ([accountManager checkPhoneNumber:phoneNumber illegalInputHandler:^(NSString *message) {
            [[JTToast makeText:message] showInView:self.view size:CGSizeMake(message.length*20, 40)];
        }]) {
            if ([accountManager checkCheckcode:checkcode illegalInputHandler:^(NSString *message) {
                [[JTToast makeText:message] showInView:self.view size:CGSizeMake(message.length*20, 40)];
            }]) {
                KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
                [accountManager registerWithPhoneNubmer:phoneNumber realName:realName checkcode:checkcode successHandler:^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        KFDSetNicknamePasswordViewController* setNicknamePasswordVC=[[UIStoryboard storyboardWithName:@"SetNicknamePassword" bundle:nil] instantiateViewControllerWithIdentifier:@"KFDSetNicknamePasswordViewController"];
                        setNicknamePasswordVC.sourceViewController=self.sourceViewController;
                        [self.navigationController pushViewController:setNicknamePasswordVC animated:YES];
                    });
                } failureHandler:^(KFDResponseBody *response) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[JTToast makeText:response.message] showInView:self.view size:CGSizeMake(response.message.length*20, 40)];
                    });
                }];
            }
        }
    }
#endif
}

-(void)goBack
{
    if (self.sourceViewController) {
        [self.navigationController popToViewController:self.sourceViewController animated:YES];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

#pragma mark - Text field delegate

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
    NSInteger length=textField.text.length-range.length+string.length;
    switch (textField.tag) {
        case PHONE_NUMBER_TEXT_FIELD:
        {
            if ([accountManager phoneNumberLengthExceedLimit:length]) {
                return NO;
            }
            return YES;
        }
        case CHECKCODE_TEXT_FIELD:
        {
            if ([accountManager checkcodeLengthExceedLimit:length]) {
                return NO;
            }
            return YES;
        }
    }
    return YES;
}

@end
